package com.bigscreen.controller;

import com.bd1904.common.CommonUtil;
import com.bigscreen.service.BigScreenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

//该注解标识当前类是webSocket的服务端实现类
@ServerEndpoint("/web_socket/all_amt")
@Controller
public class RealTimeTotalAmtWebSocket {
    //连接建立成功  调用的方法
    @OnOpen
    public void onOpen(Session session){
        System.out.println("连接建立成功");
    }
    //连接关闭 调用的方法
    @OnClose
    public void onClose(){
        System.out.println("连接关闭啦");
    }

    private static BigScreenService bigScreenService;

    //webSocket 多线程 使用方法注入
    @Autowired
    public void setBigScreenService(BigScreenService bigScreenService){
        RealTimeTotalAmtWebSocket.bigScreenService=bigScreenService;
        //this.setBigScreenService(bigScreenService);
    }

    //收到客户端消息后调用的方法
    @OnMessage
    public void onMesage(String message,Session session){
        //需要向客户端发送消息，死循环，每隔1秒发送一次数据
        while(true){
            String totalAmt = bigScreenService.fetchTotalAmt();
            System.out.println("total:-->" + totalAmt);
            //推送到远程客户端
            try {
                session.getBasicRemote().sendText(totalAmt);

                CommonUtil.sleep(300);//封装的休眠方法
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }

}
